package com.umeox.zikrringtest.single_test.gsensor

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.LayoutInflater
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.umeox.base.BaseRecyclerViewAdapter
import com.umeox.base.BaseViewHolder
import com.umeox.sdk_ring.RingProxy
import com.umeox.sdk_ring.UMRingSdk
import com.umeox.sdk_ring.protocol.IEmptyAppProtocol
import com.umeox.zikrringtest.R
import com.umeox.zikrringtest.databinding.ActivitySensorTestBinding
import java.io.File
import java.util.Date
import java.util.LinkedList
import java.util.TimeZone
import kotlin.math.abs

class SensorTestActivity : AppCompatActivity(), IEmptyAppProtocol {

    private lateinit var mBinding: ActivitySensorTestBinding

    private lateinit var ringProxy: RingProxy

    private var records: LinkedList<GSensorInfo> = LinkedList()

    private var adapter = GSensorInfoListAdapter(records)

    private val handler = Handler(Looper.getMainLooper())

    private var follow = true

    private var connectState = false

    private val inputDialog by lazy {
        InputDialog(this).apply {
            setOnConfirmListener { name ->
                val file = File(Environment.getExternalStorageDirectory(), "$name.txt")
                val writer = file.bufferedWriter()
                records.forEachIndexed { index, gSensorInfo ->
                    writer.write(gSensorInfo.printInfo(index))
                    writer.newLine()
                }
                writer.close()
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private var refreshTask = Runnable {
        adapter.notifyDataSetChanged()
        if (follow && connectState) {
            mBinding.rv.scrollToPosition(adapter.itemCount - 1)
        }
        startRefreshTask()
    }

    private fun startRefreshTask() {
        handler.postDelayed(refreshTask, 1000L)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化 DataBinding
        mBinding = DataBindingUtil.inflate(
            LayoutInflater.from(this),
            R.layout.activity_sensor_test, null, false
        )

        // 绑定生命周期管理
        mBinding.lifecycleOwner = this

        // 设置布局
        setContentView(mBinding.root)

        val macAddress = intent.getStringExtra("macAddress") ?: ""
        mBinding.tvAddress.text = macAddress

        mBinding.rv.adapter = adapter

        mBinding.ivFollow.setOnClickListener {
            if (follow) {
                follow = false
                mBinding.ivFollow.imageTintList =
                    ColorStateList.valueOf(Color.parseColor("#352F2F"))
            } else {
                follow = true
                mBinding.ivFollow.imageTintList =
                    ColorStateList.valueOf(Color.parseColor("#2D73CC"))
            }
        }

        mBinding.ivSave.setOnClickListener {
            if (connectState) {
                val dialog =
                    AlertDialog.Builder(this).setTitle("提示").setMessage("请断开连接后再保存数据！")
                        .setNegativeButton("确定") { dialog, _ ->
                            dialog.dismiss()
                        }
                dialog.create().show()
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    if (!Environment.isExternalStorageManager()) {
                        startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
                    } else {
                        inputDialog.showDialog()
                    }
                } else {
                    requestPermissions(
                        arrayOf(
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                        ), 1000
                    )
                }
            }
        }

        ringProxy = UMRingSdk.createRingProxy(macAddress).apply {
            addAppProtocolObserver(this@SensorTestActivity)
        }

        //连接
        mBinding.btConnect.setOnClickListener {
            ringProxy.connectDevice()
        }

        //断开连接
        mBinding.btDisConnect.setOnClickListener {
            ringProxy.disConnectDevice()
        }

        mBinding.btClear.setOnClickListener {
            handler.post {
                records.clear()
                adapter.notifyDataSetChanged()
            }

        }
    }

    override fun onTimeSyncCallback() {
        ringProxy.syncCurrentTimeAndTimeFormat(null, null, true, getCurrentTimeZone())
    }

    /**
     * 可简化计算过程 为了方便理解 没有简化
     */
    private fun getCurrentTimeZone(): Double {
        val now = Date()
        val zone = TimeZone.getDefault()
        val id = zone.id
        val timeZone1 = TimeZone.getTimeZone(id)
        val timeZone2 = TimeZone.getTimeZone("UTC")

        val currentOffsetFromUTC = if (timeZone1.inDaylightTime(now)) {
            timeZone1.dstSavings + timeZone1.rawOffset
        } else {
            0 + timeZone1.rawOffset
        }

        val serverOffsetFromUTC = if (timeZone2.inDaylightTime(now)) {
            timeZone2.dstSavings + timeZone2.rawOffset
        } else {
            0 + timeZone2.rawOffset
        }

        val isNegativeNumber = currentOffsetFromUTC < 0

        val secondOffset = abs(abs(serverOffsetFromUTC) - currentOffsetFromUTC) / 1000
        val hour = secondOffset / 3600
        val minute = secondOffset % 3600 / 60
        return if (isNegativeNumber) {
            -1.0 * (hour + minute / 60.0)
        } else {
            hour + minute / 60.0
        }
    }

    override fun onConnected() {
        connectState = true
        mBinding.cv.setCardBackgroundColor(getColor(R.color.connect))
        startRefreshTask()
    }

    override fun onDisconnected() {
        connectState = false
        mBinding.cv.setCardBackgroundColor(getColor(R.color.dis_connect))
        handler.removeCallbacks(refreshTask)
    }

    override fun onGSensorDataReport(datetime: String, packageIndex: Int, datas: Array<String>) {
        records.add(GSensorInfo(datetime, packageIndex, datas))
    }

    override fun onDestroy() {
        super.onDestroy()
        ringProxy.destroy()
    }
}

class GSensorInfoListAdapter(var list: LinkedList<GSensorInfo>) :
    com.umeox.base.BaseRecyclerViewAdapter<GSensorInfo>() {
    override fun getLayoutId(viewType: Int): Int = R.layout.item_sensor

    override fun getDataByPosition(position: Int): GSensorInfo = list[position]

    override fun getTotalSize(): Int = list.size

    override fun convert(holder: com.umeox.base.BaseViewHolder, data: GSensorInfo, position: Int) {
        holder.getView<TextView>(R.id.item_index).text = "$position"
        holder.getView<TextView>(R.id.item_datetime).text = data.datatime
        holder.getView<TextView>(R.id.item_package_index).text = "${data.packageIndex}"
        holder.getView<TextView>(R.id.item_datas).text = data.datas.joinToString()
    }
}